﻿using NCP.Model;
using NCP.Service;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using System.Configuration;
namespace WebAPI.Controllers
{
    public class LimitDrugAPIController : ApiController
    {
        
        private ApiTools tool = new ApiTools();
        private LimitDrugAPIService _service=new LimitDrugAPIService();
        string AlertInfo = ConfigurationManager.AppSettings["AlertInfo"].ToString();


        //是否限制用药 drugCode 非中选药品编码 deptCode 科室编码  inpatientNo 住院号
        [HttpPost]
        public HttpResponseMessage IsLimitDrug([FromBody] List<PostDate> dt)
        {
            //PostDate dt = JsonConvert.DeserializeObject<PostDate>(postDate);
            bool flag = false;//false 提醒 true 限制
            string msg = "";
            string logmsg = "";
            foreach (PostDate p in dt)
            {
                
                string inpatientNo = p.inpatientNo;
                string drugCode = p.drugCode;
                string deptCode = p.deptCode;
                //1、先判断该药品是否属于非中选药品
                int cnt = _service.IsUnChoseDrug(drugCode);
                if (cnt == 0)//如果不是非中选药品则不判断
                {
                    LimitDrug limitDrugDept = new LimitDrug();
                    limitDrugDept = _service.GetLimitDrug(drugCode, deptCode, "1");
                    PhaBaseInfo pb = new PhaBaseInfo();
                    pb = _service.GetPhaBaseInfo(drugCode);
                    if (limitDrugDept != null)
                    {
                        if (limitDrugDept.Status == "1")//如果被限制了，则质控
                        {
                            LimitDrug limitDrugPatient = new LimitDrug();
                            limitDrugPatient = _service.GetLimitDrug(drugCode, inpatientNo, "2");
                            if (limitDrugPatient != null && limitDrugPatient.Status == "2")//如果放开个人 则可以开立
                            {
                                logmsg += "住院号：" + inpatientNo + " 科室：" + deptCode + "；" + pb.DrugName + "放开该患者使用\r\n";

                            }
                            else
                            {
                                //return tool.MsgFormat(ApiTools.ResponseCode.质控, "科室不能开立该药品", "1");
                                msg += pb.DrugName + AlertInfo+"\r\n";
                                logmsg += "住院号：" + inpatientNo + " 科室：" + deptCode + "；" + pb.DrugName + AlertInfo+ "\r\n";
                                flag = true;
                            }
                        }
                    }
                    else
                    {
                        LimitDrug limitDrugPatient = new LimitDrug();
                        limitDrugPatient = _service.GetLimitDrug(drugCode, inpatientNo, "2");
                        if (limitDrugPatient != null && limitDrugPatient.Status == "1")//如果科室未限制，限制个人
                        {
                            msg += pb.DrugName + AlertInfo+ "\r\n";
                            logmsg += "住院号：" + inpatientNo + " 科室：" + deptCode + "；" + pb.DrugName + AlertInfo+ "\r\n";
                            flag = true;

                        }
                    }
                    //如果限制时间
                    LimitTime limitTime = _service.GetLimitTime(drugCode);
                    if (limitTime != null)
                    {
                        int isallow = _service.IsAllow(inpatientNo, drugCode, limitTime.LimitDate, limitTime.Days);
                        //如果为0 则不允许开立
                        if (isallow == 0)
                        {
                            //判断是否放开患者
                            LimitDrug limitDrugPatient = new LimitDrug();
                            limitDrugPatient = _service.GetLimitDrug(drugCode, inpatientNo, "2");
                            if (limitDrugPatient != null && limitDrugPatient.Status == "2")//如果放开个人 则可以开立
                            {
                                logmsg += "住院号：" + inpatientNo + " 科室：" + deptCode + "；" + pb.DrugName + "放开该患者使用\r\n";
                            }
                            else
                            {
                                flag = true;
                                msg += pb.DrugName + AlertInfo+ "\r\n";
                                logmsg += "住院号：" + inpatientNo + " 科室：" + deptCode + "；" + pb.DrugName + AlertInfo+"\r\n";
                            }
                        }
                    }
                }
                else  //2、属于则判断数量及比例是否达标
                {
                    //判断该科室是否分配任务
                    var groupMission = _service.GetGroupMission(drugCode, deptCode);
                    var choseAndUnchoseDrugInfo = _service.GetChoseAndUnchoseDrugInfo(drugCode);
                    if (groupMission == null)
                    {
                        //return tool.MsgFormat(ApiTools.ResponseCode.未质控, "未质控", "0");
                        logmsg += "住院号：" + inpatientNo + " 科室：" + deptCode + "；" + choseAndUnchoseDrugInfo.UnChosedrugName + "对应的中选药品"+ choseAndUnchoseDrugInfo.ChosedrugName + "未分配任务\r\n";
                    }
                    else
                    {
                        //获取药品在该科室的完成数量及比例
                        QtyAndRate drug = _service.GetQtyAndRate(drugCode, deptCode);

                        if (groupMission.Qyt < drug.choseqty && groupMission.Rate < drug.rate)//科室任务量及比例已完成，则不质控
                        {
                            //flag = false;
                            //return tool.MsgFormat(ApiTools.ResponseCode.未质控, "科室任务已完成", "0");
                            logmsg += "住院号：" + inpatientNo + " 科室：" + deptCode + "；" + choseAndUnchoseDrugInfo.UnChosedrugName + "科室任务已完成\r\n";
                        }
                        else//科室未完成任务
                        {
                            //判断科室是否放开限制
                            LimitDrug limitDrugDept = new LimitDrug();
                            limitDrugDept = _service.GetLimitDrug(drugCode, deptCode, "1");
                            LimitDrug limitDrugPatient = new LimitDrug();
                            limitDrugPatient = _service.GetLimitDrug(drugCode, inpatientNo, "2");
                            if (limitDrugDept == null || limitDrugDept.Status == "1")//如果未维护或维护了限制
                            {

                                if (limitDrugPatient != null && limitDrugPatient.Status == "2")//如果放开个人
                                {
                                    logmsg += "住院号：" + inpatientNo + " 科室：" + deptCode + "；" + choseAndUnchoseDrugInfo.UnChosedrugName + "科室任务未完成，但放开该患者\r\n";
                                    //return tool.MsgFormat(ApiTools.ResponseCode.未质控, "科室任务未完成，但放开该患者，药品编码：" + drugCode, "0");
                                }
                                else
                                {
                                    //如果限制时间
                                    LimitTime limitTime = _service.GetLimitTime(drugCode);
                                    if (limitTime != null)
                                    {
                                        int isallow = _service.IsAllow(inpatientNo, drugCode, limitTime.LimitDate, limitTime.Days);
                                        //如果为0 则不允许开立
                                        if (isallow > 0)
                                        {
                                            //flag = false;
                                            //return tool.MsgFormat(ApiTools.ResponseCode.未质控, "科室任务未完成，但已开立该药品患者允许开立", "0");
                                            logmsg += "住院号：" + inpatientNo + " 科室：" + deptCode + "；" + choseAndUnchoseDrugInfo.UnChosedrugName + "科室任务未完成，但已开立该药品患者允许开立\r\n";
                                        }
                                        else
                                        {

                                            //if (groupMission.Qyt < drug.choseqty && groupMission.Rate < drug.rate)
                                            //{
                                            //    msg += "集采非中选药品"+ choseAndUnchoseDrugInfo.UnChosedrugName + "按政策限量使用，科室任务量（按天累计进度计算）还差：" + (Math.Round(drug.choseqty, 2) - groupMission.Qyt) + ",比例为：" + Math.Round(groupMission.Rate, 2) + "%,未达到：" + drug.rate + "%任务占比,请开立中选药品 " + choseAndUnchoseDrugInfo.ChosedrugName + "\n";
                                            //}
                                            //else if (groupMission.Qyt < drug.choseqty && groupMission.Rate > drug.rate)
                                            //{
                                            //    msg += choseAndUnchoseDrugInfo.UnChosedrugName + "的使用，中选药品科室任务量（按天累计进度计算）还差：" + (Math.Round(drug.choseqty, 2) - groupMission.Qyt) + ",请开立中选药品 " + choseAndUnchoseDrugInfo.ChosedrugName + "\n";
                                            //}
                                            //else if (groupMission.Qyt > drug.choseqty && groupMission.Rate < drug.rate)
                                            //{
                                            //    msg += choseAndUnchoseDrugInfo.UnChosedrugName + "的使用，中选药品科室任务量（按天累计进度计算）,比例为：" + Math.Round(groupMission.Rate, 2) + "%,未达到：" + drug.rate + "%任务占比,请开立中选药品 " + choseAndUnchoseDrugInfo.ChosedrugName + "\n";
                                            //}
                                            msg += "集采非中选药品" + choseAndUnchoseDrugInfo.UnChosedrugName + "按政策限量使用，科室任务量未完成，请优先选择集采中选药品" + choseAndUnchoseDrugInfo.ChosedrugName + "\r\n";

                                            logmsg += "住院号：" + inpatientNo + " 科室：" + deptCode + "；" + "集采非中选药品" + choseAndUnchoseDrugInfo.UnChosedrugName + "按政策限量使用，科室任务量未完成，请优先选择集采中选药品" + choseAndUnchoseDrugInfo.ChosedrugName+"\r\n";

                                        }
                                    }
                                    else
                                    {
                                        //if (groupMission.Qyt < drug.choseqty && groupMission.Rate < drug.rate)
                                        //{
                                        //    msg += choseAndUnchoseDrugInfo.UnChosedrugName + "的使用，中选药品科室任务量（按天累计进度计算）还差：" + (Math.Ceiling(groupMission.Qyt) - Math.Ceiling(drug.choseqty)) + ",比例为：" + Math.Round(groupMission.Rate, 2) + "%,未达到：" + drug.rate + "%任务占比,请开立中选药品 " + choseAndUnchoseDrugInfo.ChosedrugName + "\n";
                                        //}
                                        //else if (groupMission.Qyt > drug.choseqty && groupMission.Rate < drug.rate)
                                        //{
                                        //    msg += choseAndUnchoseDrugInfo.UnChosedrugName + "的使用，中选药品科室任务量（按天累计进度计算）还差：" + (Math.Ceiling(groupMission.Qyt) - Math.Ceiling(drug.choseqty)) + ",请开立中选药品 " + choseAndUnchoseDrugInfo.ChosedrugName + "\n";
                                        //}
                                        //else if (groupMission.Qyt < drug.choseqty && groupMission.Rate > drug.rate)
                                        //{
                                        //    msg += choseAndUnchoseDrugInfo.UnChosedrugName + "的使用，中选药品科室任务量（按天累计进度计算）,比例为：" + drug.rate + "%,未达到：" + Math.Round(groupMission.Rate, 2) + "%任务占比,请开立中选药品 " + choseAndUnchoseDrugInfo.ChosedrugName + "\n";
                                        //}
                                        msg += "集采非中选药品" + choseAndUnchoseDrugInfo.UnChosedrugName + "按政策限量使用，科室任务量未完成，请优先选择集采中选药品" + choseAndUnchoseDrugInfo.ChosedrugName+ "\r\n";

                                        logmsg += "住院号：" + inpatientNo + " 科室：" + deptCode + "；" + "集采非中选药品" + choseAndUnchoseDrugInfo.UnChosedrugName + "按政策限量使用，科室任务量未完成，请优先选择集采中选药品" + choseAndUnchoseDrugInfo.ChosedrugName + "\r\n";
                                    }

                                }


                            }
                            else//维护了放开科室限制
                            {
                                //判断是否限制个人

                                if (limitDrugPatient != null && limitDrugPatient.Status == "1")//如果限制个人
                                {
                                    flag = true;
                                    msg += "该患者被限制不允许开立该药品\r\n";
                                    logmsg += "住院号：" + inpatientNo + " 科室：" + deptCode + "；" + choseAndUnchoseDrugInfo.UnChosedrugName + "该患者被限制不允许开立该药品\r\n";
                                    //return tool.MsgFormat(ApiTools.ResponseCode.质控, "该患者被限制不允许开立该药品", "1");
                                }
                                // return tool.MsgFormat(ApiTools.ResponseCode.未质控, "科室任务未完成，但放开科室限制", "0");

                            }

                        }
                    }
                }
            }
            if (msg == "")
            {
                if (logmsg != "")
                {
                    WriteLog(logmsg);
                }
                return tool.MsgFormat(ApiTools.ResponseCode.未质控, "未质控", "0");
            }
            else if (msg != "" && flag == true)
            {
                if (logmsg != "")
                {
                    WriteLog(logmsg);
                }
                return tool.MsgFormat(ApiTools.ResponseCode.限制, msg, "2");
            }
            else
            {
                if (logmsg != "")
                {
                    WriteLog(logmsg);
                }
                return tool.MsgFormat(ApiTools.ResponseCode.提醒, msg, "1");
            }
            
        }

        public void WriteLog(string message)
        {
            string logtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string logfilename = "NCPlog" + DateTime.Now.ToString("yyyyMMdd") + ".txt";
            //string savePath =System.Web.HttpContext.Current.Server.MapPath(@"log");
            //string savePath = AppDomain.CurrentDomain.BaseDirectory + @"log\";
            string savePath = "C:\\NCPlog";
            if (!System.IO.Directory.Exists(savePath))
            { //需要注意的是，需要对这个物理路径有足够的权限，否则会报错    
                //另外，这个路径应该是在网站之下，而将网站部署在C盘却把上传文件保存在D盘 
                System.IO.Directory.CreateDirectory(savePath);
            }
            string Logmessage =  "时间：" + logtime + "\r\n" + "message：" + message + "\r\n";
            Logmessage += "*****************************************************************************************\r\n";
            //System.IO.StreamWriter fd = new System.IO.StreamWriter(savePath + "\\" + logfilename, true, System.Text.Encoding.Default);
            //fd.WriteLine(Logmessage);
            //fd.Flush();
            //fd.Close();

            FileStream fs = new FileStream(savePath + "\\" + logfilename, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
            StreamWriter sr = new StreamWriter(fs, Encoding.Default);
            sr.WriteLine(Logmessage);
            sr.Close();
            fs.Close();

        }
    }
}